<template>
  <div class="login-container" v-title data-title="iWMS-终端登录">
    <!-- <div class="login-left">
      <img src="../assets/images/imgs/login_img.png">
    </div> -->
    <div class="login-box">
      <!-- 头像 -->
      <div class="avatar-box">
        <img src="../assets/login_logo.png" />
      </div>
      <!-- 标题 -->
      <div class="title">iWMS-终端登录</div>
      <!-- 表单 -->
      <el-form
        ref="loginFormRef"
        class="login-form"
        :model="loginForm"
        :rules="loginFormRules"
      >
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="loginForm.username"
            prefix-icon="iconfont icon-user"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            show-password
            prefix-icon="iconfont icon-3702mima"
            v-model="loginForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="area">
          <el-select
            v-model="loginForm.area"
            placeholder="请选择工作台"
            style="width: 100%"
            disabled
          >
            <el-option
              v-for="item in areaInfo"
              :label="item.WbName"
              :value="item.WbId"
              :key="item.WbId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 				<el-form-item prop="VcCode">
					<el-input placeholder="验证码" prefix-icon="iconfont icon-3702mima" style="width: 60%;"
						v-model="loginForm.VcCode"></el-input>
					<img :src="vccode" width="110px" height="50px" @click="VcCodeFun()" />
				</el-form-item> -->
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="tologin"
            >登 录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100%;
  // background: #93defe;
  // background: url(../assets/images/bg/bg1.jpg) no-repeat;
  background: url(../assets/bg5.jpg) no-repeat;
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .login-left {
    margin-right: 10%;
  }

  .login-box {
    width: 400px;
    height: 360px;
    background: #fff;
    padding: 50px;
    border-radius: 6px;
    box-sizing: border-box;
    position: relative;

    .avatar-box {
      width: 120px;
      height: 120px;
      // border: 5px solid #93defe;
      border-radius: 100px;
      text-align: center;
      line-height: 110px;
      position: absolute;
      top: -60px;
      right: 140px;
      background: #fff;

      & > img {
        width: 120px;
        height: 100px;
      }
    }

    .title {
      position: absolute;
      top: 60px;
      left: 50%;
      transform: translate(-50%);
      font-size: 18px;
      color: #444;
    }

    .login-form {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translate(-50%);
      padding: 0 20px;
      width: 80%;
      box-sizing: border-box;

      .login-btn {
        width: 100%;
      }

      .el-form-item {
        /deep/.el-form-item__content {
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
</style>
<script>
import {
  login,
  loginPrint,
  areaInfo,
  appPost,
  VerificationCode,
  POSTLocationInfo,
} from "@/api/api";
import { ParameterCalcPackage } from "../utils/ParameterCalcPackage.js";
export default {
  name: "login",
  data() {
    return {
      // 表单的数据绑定对象
      loginForm: {
        username: "",
        password: "",
        area: "",
        VcCode: "",
      },
      vccode: "",
      areaInfo: [],
      areaInfoList: [],
      userInfo: {},
      user_id: "",
      // 表单的校验规则
      loginFormRules: {
        username: [
          {
            required: true,
            message: "请输入登录账户",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入登录密码",
            trigger: "blur",
          },
          {
            min: 4,
            max: 15,
            message: "长度在 4 到 15 个字符",
            trigger: "blur",
          },
        ],
        area: [
          {
            required: true,
            message: "请选择一个库区登录",
            trigger: "change",
          },
        ],
        VcCode: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    window.addEventListener("keydown", this.keyDown);
    // this.userInfo.UserId = "CH";
    // this.userInfo.CfgId = "06";
    // this.userInfo.WbId = "SPS_W1";
    // this.userInfo.WbInfo = {
    //   MaxTaskCount: 0,
    //   Status: 1,
    //   WbId: "SPS_W1",
    // };
    // sessionStorage.setItem("userInfo", JSON.stringify(this.userInfo));
  },
  methods: {
    keyDown(e) {
      if (e.keyCode === 13) {
        this.tologin();
      }
    },
    getWbId() {
      var wbidurl = "ws://localhost:13145/About";
      var ws = new WebSocket(wbidurl);
      ws.onerror = (event) => {
        this.$notify({
          title: "警告",
          message: "WET未开启,无法获取工作台信息登录",
          type: "error",
          duration: 0,
        });
        this.$message({
          message: "WET未开启,无法获取工作台信息登录",
          type: "error",
        });
      };
      const than = this;
      ws.onopen = function () {
        // connection opened
        var command = {
          Id: new Date().getTime().toString(),
          Type: "WB",
        };
        ws.send(JSON.stringify(command));
      };
      ws.onmessage = function (e) {
        // message received
        const data = JSON.parse(e && e.data);
        console.log(
          than.areaInfoList,
          than.areaInfoList.indexOf(data.Data.WbId)
        );
        if (
          data.Code == 0 &&
          data.Data !== null &&
          than.areaInfoList.indexOf(data.Data.WbId) > -1
        ) {
          than.loginForm.area = data.Data.WbId;
          //   than.tologin()
        } else {
          //   than.audioPlay('error')
          var message = "";
          if (
            data.Data !== null &&
            than.areaInfoList.indexOf(data.Data.WbId) == -1
          ) {
            message = "WET工作台配置不存在";
          } else if (data.Data == null) {
            message = "WET配置错误";
          } else {
            message = "WET配置错误";
          }
          than.$message({
            message: message,
            type: "error",
          });
        }
      };
    },
    tologin() {
      if (!this.loginForm.area) {
        this.getWbId();
      }
      // 判断是否校验成功
      // this.$refs.loginFormRef.validate(valid => {
      const param = {
        UserId: this.loginForm.username,
        UserPwd: this.loginForm.password,
        VcCode: this.loginForm.VcCode,
        WbId: this.loginForm.area,
      };
      // if (valid) {
      this.loading = true;
      var dateParam = ParameterCalcPackage("gz.wms.app.login", param);
      // appPost(dateParam.getData, dateParam.dateParam).then(res => {
      login(param)
        .then((res) => {
          const result = res.data;
          console.log("login", res.data);
          if (result.code === 0) {
            this.userInfo.UserId = this.loginForm.username;
            this.userInfo.WbId = this.loginForm.area;
            for (let i = 0; i < this.areaInfo.length; i++) {
              if (this.areaInfo[i].WbId === this.loginForm.area) {
                this.userInfo.WbInfo = this.areaInfo[i];
              }
            }
            this.GetPrintInfo(result.data.UserId);
          } else {
            this.$message({
              message: result.message,
              type: "error",
              offset: 200,
            });
            this.VcCodeFun();
          }
        })
        .catch(() => {
          this.loading = false;
        });
      // }
      // })
    },

    GetPrintInfo(value) {
      const param = {
        time: Date.parse(new Date()),
        userId: value,
      };
      loginPrint(param).then((res) => {
        this.loading = false;
        console.log("res.data", res.data);
        const result = res.data;
        if (result.code === 0) {
          this.userInfo.CfgName = result.data.CfgName;
          this.userInfo.CfgId = result.data.CfgId;
          this.userInfo.ConnectMode = result.data.ConnectMode;
          this.userInfo.Url = result.data.Url;
          this.userInfo.RemoteUrl = result.data.RemoteUrl;
          sessionStorage.setItem("userInfo", JSON.stringify(this.userInfo));
          this.getSOWLocationId();
        } else {
          this.$message({
            message: result.message,
            type: "warning",
            offset: 200,
          });
        }
      });
    },
    getSOWLocationId() {
      const params = {
        UserId: this.userInfo.UserId,
        WbId: this.userInfo.WbId,
        time: Date.parse(new Date()),
      };
      POSTLocationInfo(params).then((res) => {
        if (res.data.code === 0 && res.data.data.length >= 1) {
          sessionStorage.removeItem("SOWLocationId");
          sessionStorage.setItem(
            "SOWLocationId",
            JSON.stringify(res.data.data)
          );
        } else {
          this.$message({
            message: "登录工作台无播种库位",
            type: "info",
          });
        }
      });
      this.$router.push("/index");
    },
    async VcCodeFun() {
      const param = {
        time: Date.parse(new Date()),
      };
      var dateParam = ParameterCalcPackage("gz.wms.app.vcode", param);
      appPost(dateParam.getData, dateParam.dateParam).then((res) => {
        // VerificationCode(param).then(res => {
        const result = res.data;
        if (result.code === 0) {
          this.vccode = "data:image/png;base64," + result.data[0].Code;
        }
      });
    },
  },
  created() {
    areaInfo().then((res) => {
      const result = res.data;
      if (result.code === 0) {
        this.areaInfo = result.data;
        this.areaInfo.forEach((item) => {
          this.areaInfoList.push(item.WbId);
        });
        this.getWbId();
      } else {
        this.$message({
          message: result.message,
          type: "warning",
          offset: 200,
        });
      }
    });
    // this.VcCodeFun()
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
};
</script>
